package com.cbgolf.oa.views;


import static com.cbgolf.oa.R.color.bg_gray_deep;
import static com.cbgolf.oa.R.id.root;
import static com.cbgolf.oa.util.ScreenUtil.getWidth;

import android.app.Activity;
import android.graphics.drawable.ColorDrawable;
import android.support.v4.content.ContextCompat;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.widget.AbsListView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;
import butterknife.ButterKnife;
import com.cbgolf.oa.R;
import com.cbgolf.oa.adapter.LeftAdapter;
import com.cbgolf.oa.adapter.RightAdapter;
import com.cbgolf.oa.adapter.RightDetailsAdapter;
import com.cbgolf.oa.base.BaseView;
import com.cbgolf.oa.entity.PointBean;
import com.cbgolf.oa.entity.ShopBean;
import com.cbgolf.oa.presenter.IShopPresenter;
import com.cbgolf.oa.util.AnimaUtil;
import com.cbgolf.oa.util.DataUtil;
import com.cbgolf.oa.util.DialogUtil;
import com.cbgolf.oa.util.ErrorUtil;
import com.cbgolf.oa.util.PopUtil;
import com.cbgolf.oa.util.ScreenUtil;
import com.cbgolf.oa.util.TextUtil;
import com.cbgolf.oa.util.TypeUtil;
import com.cbgolf.oa.util.Util;
import com.cbgolf.oa.util.ViewUtils;
import com.cbgolf.oa.widget.autolayout.utils.AutoUtil;
import com.zhy.base.adapter.ViewHolder;
import com.zhy.base.adapter.abslistview.CommonAdapter;
import java.util.ArrayList;
import java.util.List;
import org.xutils.view.annotation.ViewInject;

/**
 * Created by lq on 2017/10/31.
 */

public class ShoppingView extends BaseView implements RightDetailsAdapter.INumWorker,
    LeftAdapter.IClickListener {

  @ViewInject(R.id.topBack_ll)
  private View topBack;
  @ViewInject(R.id.title_tv)
  private TextView titleTv;
  @ViewInject(R.id.topRight_iv)
  private ImageView topRight;

  //
  @ViewInject(R.id.a_shop_point_tv)
  private TextView pointTv;
  @ViewInject(R.id.a_shop_point_change_tv)
  private TextView pointChangeTv;
  @ViewInject(R.id.a_shop_user_tv)
  private TextView userTv;
  @ViewInject(R.id.a_shop_cardnum_et)
  private EditText cardNumEt;
  @ViewInject(R.id.a_shop_num_sure_tv)
  private TextView numSureTv;
  //bottom
  @ViewInject(R.id.a_shop_num_tv)
  private TextView shopNumTv;
  @ViewInject(R.id.a_shop_money_tv)
  private TextView moneyTv;
  @ViewInject(R.id.a_shop_serve_money_tv)
  private TextView serviceMoneyTv;
  @ViewInject(R.id.a_shop_discount_money_tv)
  private TextView disCountTv;
  @ViewInject(R.id.a_shop_prefre_money_tv)
  private TextView youHunTv;
  @ViewInject(R.id.a_shop_car_rl)
  private View shopCarView;
  @ViewInject(R.id.a_shop_car_iv)
  private ImageView shopCarIv;
  //
  @ViewInject(R.id.a_shop_submit_tv)
  private TextView subMitTv;


  @ViewInject(R.id.a_shopping_left_listview)
  private ListView listViewLeft;
  @ViewInject(R.id.a_shopping_right_listview)
  private ListView listViewRight;
  //
  @ViewInject(R.id.a_shop_cardnum_tv)
  private TextView cardNumTv;
  //
  @ViewInject(R.id.a_shop_card_userinfo_ll)
  private View cardUserView;
  @ViewInject(R.id.a_shop_card_username_tv)
  private TextView cardUsernameTv;
  @ViewInject(R.id.a_shop_card_userid_tv)
  private TextView cardUserIdTv;
  //
  @ViewInject(R.id.a_shopping_bottom_ll)
  private View bottomView;

  @ViewInject(R.id.root)
  private LinearLayout rootView;


  //
  @ViewInject(R.id.a_shopping_data_ll)
  private View dataView;
  @ViewInject(R.id.g_error_ll)
  private View errorView;
  @ViewInject(R.id.g_error_tv)
  private TextView errorTv;


  //    private LeftSectionedAdapter leftAdapter;
  private LeftAdapter leftAdapter;
  private RightAdapter rightAdapter;

  private ShopBean bean;
  private List<ShopBean.goodsDetails> listShopCar = new ArrayList<>();
  private String pointCode;

  @Override
  public void click(int position) {
    listViewRight.setSelection(position);
  }


  private IShopPresenter worker;

  public ShoppingView(Activity act, IShopPresenter worker) {
    this.worker = worker;
    ViewUtils.autoInjectAllField(this, act);
    super.init(act);
  }

  @Override
  protected void setViews() {
    titleTv.setText(TextUtil.Text(DataUtil.getCourseName()));
    topRight.setImageResource(R.mipmap.lishi);
    topRight.setVisibility(View.VISIBLE);
    userTv.setText("开单人:" + DataUtil.getUserName());
    leftAdapter = new LeftAdapter(context, this);
    listViewLeft.setAdapter(leftAdapter);
    rightAdapter = new RightAdapter(context, this);
    listViewRight.setAdapter(rightAdapter);

  }

  @Override
  protected void setListener() {
    topBack.setOnClickListener(v -> worker.back());
    topRight.setOnClickListener(v -> worker.ClickTopRight());
    pointChangeTv.setOnClickListener(v -> worker.ClickChangePoint());
    numSureTv.setOnClickListener(v -> {
      if (!Util.isEquals("重新开单", numSureTv.getText().toString())) {
        String num = cardNumEt.getText().toString().trim();
        if (Util.isNull(num)) {
          Util.show("请输入卡号");
          return;
        }
        worker.ClickNumOk(num);
        return;
      }
      cardNumEt.setVisibility(View.VISIBLE);
      isSelectCardFail = true;
      cardNumTv.setText("");
      cardUserView.setVisibility(View.GONE);
      cardUsernameTv.setText("姓名:");
      cardUserIdTv.setText("身份:");
      numSureTv.setText("确认");

    });

////右边ListView滑动位置来更新左边ListView分类信息的位置切换
    listViewRight.setOnScrollListener(new AbsListView.OnScrollListener() {

      @Override
      public void onScrollStateChanged(AbsListView arg0, int arg1) {

      }

      @Override
      public void onScroll(AbsListView view, int firstVisibleItem,
          int visibleItemCount, int totalItemCount) {
//                if (DataUtil.getMapBoolean(mapLeft, firstVisibleItem)) return;
//                leftAdapter.setSelect(firstVisibleItem);
        listViewLeft.setSelection(firstVisibleItem);

      }
    });
    shopCarView.setOnClickListener(v -> {
      showShopCarPop();


    });
    subMitTv.setOnClickListener(v -> doSubmit());
  }

  private void doSubmit() {
    if (isSelectCardFail) {
      Util.show("请确认消费卡号");
      return;
    }
    if (Util.listIsNull(listShopCar)) {
      Util.show("请选择商品");
      return;
    }
    setSubmitEnable(false);
    String title = "开单确认";
    String msg = "您是否确认开单，开单后无法进行修改 和取消。如需操作请联系管理员。";

    DialogUtil.showKandanDialog(context, title, msg, () -> setSubmitEnable(true),
        () -> worker.ClickSubMit(listShopCar, pointCode));
  }

  private boolean isSelectCardFail = true;

  public void setSelectCardNumFail() {
    isSelectCardFail = true;
  }

  public void setSubmitEnable(boolean enable) {
    subMitTv.setEnabled(enable);
    subMitTv.setBackgroundColor(
        ContextCompat.getColor(context, enable ? R.color.bg_blue_login : bg_gray_deep));
    if (null != popSubTv) {
      popSubTv.setEnabled(enable);
      popSubTv.setBackgroundColor(
          ContextCompat.getColor(context, enable ? R.color.bg_blue_login : bg_gray_deep));
    }
  }

  private PopupWindow pop;
  private TextView popMoneyTv;
  private TextView popNumTv;
  private TextView popSubTv;

  private void showShopCarPop() {
    if (null != pop && pop.isShowing()) {
      pop.dismiss();
      pop = null;
      return;
    }
    pop = new PopupWindow();
    final View view = LayoutInflater.from(context).inflate(R.layout.pop_shoplist, null);
    final View layout = ButterKnife.findById(view, R.id.pop_shoplist_layout_rl);
    ListView listView = ButterKnife.findById(view, R.id.pop_shoplist_listview);
    final View delView = ButterKnife.findById(view, R.id.pop_shoplist_del_ll);
    popNumTv = ButterKnife.findById(view, R.id.pop_shoplist_num_tv);
    popNumTv.setText(null != bean ? TextUtil.textNumInt(bean.allNum) : "");
    popNumTv.setVisibility((null != bean && bean.allNum > 0) ? View.VISIBLE : View.GONE);
    View carView = ButterKnife.findById(view, R.id.pop_shoplist_shopcar_rl);
    popMoneyTv = ButterKnife.findById(view, R.id.pop_list_money_tv);
    popMoneyTv.setText(TextUtil.textNumFloat(moneyTv.getText().toString()));
    popSubTv = ButterKnife.findById(view, R.id.pop_list_submit_tv);
    popSubTv.setEnabled((null != bean && bean.allNum > 0));
    popSubTv.setBackgroundColor(ContextCompat.getColor(context,
        (null != bean && bean.allNum > 0) ? R.color.bg_blue_login :
            bg_gray_deep));
    AutoUtil.auto(view);
    delView.setOnClickListener(v -> {
      listShopCar.clear();
      moneyTv.setText("￥0.00");
      popMoneyTv.setText("￥0.00");
      popNumTv.setText("0");
      popNumTv.setVisibility(View.GONE);
      shopNumTv.setText("0");
      shopNumTv.setVisibility(View.GONE);
      popSubTv.setEnabled(false);
      popSubTv.setBackgroundColor(ContextCompat.getColor(context, bg_gray_deep));
    });
    carView.setOnClickListener(v -> pop.dismiss());
    CommonAdapter<ShopBean.goodsDetails> adapter = new CommonAdapter<ShopBean.goodsDetails>(
        context, R.layout.item_shopcar_list, listShopCar
    ) {
      @Override
      public void convert(final ViewHolder holder, final ShopBean.goodsDetails details) {
        if (null == details) {
          return;
        }
        holder.setText(R.id.item_shopcar_name_tv, TextUtil.Text(details.goodName));
        holder.setText(R.id.item_shopcar_price_tv,
            TextUtil.textNumFloat(TypeUtil.parseFloat(details.parValue)));
        holder.setText(R.id.item_shopcar_num_tv, TextUtil.textNumInt(details.num));
        holder.setOnClickListener(R.id.item_shopcar_reduce_ll, v -> {
          int num = details.num;
          if (num > 0) {
            num--;
            details.num = num;
            holder.setText(R.id.item_shopcar_num_tv, TextUtil.textNumInt(details.num));
            updataNum(details, -1, null);
          }
          if (num <= 0) {
            notifyDataSetChanged();
          }

        });
        holder.setOnClickListener(R.id.item_shopcar_add_ll, v -> {
          int num = details.num;
          num++;
          details.num = num;
          holder.setText(R.id.item_shopcar_num_tv, TextUtil.textNumInt(details.num));
          updataNum(details, 1, null);

        });
      }
    };
    listView.setAdapter(adapter);
    LinearLayout.LayoutParams ll = (LinearLayout.LayoutParams) layout.getLayoutParams();
    pop.setContentView(view);
    pop.setWidth(getWidth());
    pop.setHeight(ll.WRAP_CONTENT);
    pop.setOutsideTouchable(true);
    pop.setBackgroundDrawable(new ColorDrawable(0x00000000));
    pop.setTouchable(true);
    pop.setFocusable(true);
    pop.setOnDismissListener(() -> {
      ScreenUtil.LightOn(context);
    });
    view.setOnTouchListener((v, event) -> {
      int height = layout.getTop();
      int y = (int) event.getY();
      if (event.getAction() == MotionEvent.ACTION_UP) {
        if (y < height) {
          pop.dismiss();
        }
      }
      return true;
    });
    popSubTv.setOnClickListener(v -> doSubmit());
    pop.showAtLocation(context.findViewById(root),
        Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
    pop.setAnimationStyle(R.style.pop_bottom_enter);
    ScreenUtil.LightOff(context);


  }


  @Override
  public void updataNum(final ShopBean.goodsDetails m, final int num, int[] location) {
    if (null == location) {
      updataNumAndMoney(m, num);
      return;
    }
    AnimaUtil.playAnimation(context, location, shopCarIv, new AnimaUtil.IAnimWorker() {
      @Override
      public void onAnimEnd() {
        updataNumAndMoney(m, num);
      }
    });
  }

  public void updataNumAndMoney(ShopBean.goodsDetails m, int num) {
    if (null == bean) {
      bean = new ShopBean();
    }
    int all = bean.allNum + num;
    bean.allNum = all;
    subMitTv.setBackgroundColor(
        ContextCompat.getColor(context, all > 0 ? R.color.bg_blue_login : bg_gray_deep));
    shopNumTv.setVisibility(all > 0 ? View.VISIBLE : View.GONE);
    shopNumTv.setText(TextUtil.textNumInt(all > 0 ? all : 0));
    subMitTv.setEnabled(all > 0);
    if (null != popSubTv) {
      popSubTv.setBackgroundColor(
          ContextCompat.getColor(context, all > 0 ? R.color.bg_blue_login : bg_gray_deep));
      popSubTv.setEnabled(all > 0);
    }
    if (null != popNumTv) {
      popNumTv.setVisibility(all > 0 ? View.VISIBLE : View.GONE);
      popNumTv.setText(TextUtil.textNumInt(all > 0 ? all : 0));
    }
    if (null == m) {
      return;
    }
    if (num > 0) {
      if (!listShopCar.contains(m)) {
        listShopCar.add(m);
      }
    } else {
      for (int i = 0; i < listShopCar.size(); i++) {
        if (Util.isEquals(listShopCar.get(i).goodsId, m.goodsId)
            && m.num == 0) {
          listShopCar.remove(i);
          break;
        }
      }
    }
    rightAdapter.upDataUI();
    float allMoney = 0f;
    if (!Util.listIsNull(listShopCar)) {
      for (int i = 0; i < listShopCar.size(); i++) {
        allMoney += (TypeUtil.parseFloat(listShopCar.get(i).parValue) * listShopCar.get(i).num);
      }
    }
    moneyTv.setText("￥" + TextUtil.textNumFloat(allMoney));
    if (null != popMoneyTv) {
      popMoneyTv.setText("￥" + TextUtil.textNumFloat(allMoney));
    }
  }

  public void showPoint(String name) {
    pointTv.setText(TextUtil.Text(name));
  }

  public void showNoPoint(String msg) {
    pointTv.setText(TextUtil.Text(msg));
    showError(msg);

  }

  private void showError(String msg) {
//        errorView.showError(dataView, msg, new ErrorView.IReLoadListener() {
//            @Override
//            public void reload() {
//
//            }
//        });
    dataView.setVisibility(View.GONE);
    errorView.setVisibility(View.VISIBLE);
    errorTv.setText(Util.isNull(msg) ? ErrorUtil.NETERROR : msg);
    ((View) errorView.getParent()).setVisibility(View.VISIBLE);
  }

  List<ShopBean> listData;

  @Override
  public void getDataSuccess(Object obj) {
    List<ShopBean> list = (List<ShopBean>) obj;
    if (Util.listIsNull(list)) {
      showError("此营业点暂无商品信息");
      return;
    }
    listData = list;
    try {
      if (!Util.listIsNull(listShopCar)) {
        for (int i = 0; i < listData.size(); i++) {
          if (Util.listIsNull(listData.get(i).goods)) {
            continue;
          }
          for (int j = 0; j < listShopCar.size(); j++) {
            for (int x = 0; x < listData.get(i).goods.size(); x++) {
              if (Util.isEquals(listShopCar.get(j).goodsId, listData.get(i).goods.get(x).goodsId)) {
                listData.get(i).goods.get(x).num = listShopCar.get(j).num;
              }

            }
          }
        }
      }
    } catch (Exception e) {

    }
    showData();
    leftAdapter.setList(list);
    rightAdapter.setList(list);
  }

  @Override
  public void getDataFail(String msg, int code) {

  }

  private void showData() {
    dataView.setVisibility(View.VISIBLE);
    ((View) errorView.getParent()).setVisibility(View.GONE);
  }


  public void showCardNumInfo(List<ShopBean> list) {
    if (Util.listIsNull(list)) {
      DialogUtil.showMsgDialog(context, "消费卡未登记", "当前消费卡尚未登记，请您重新选择消费卡。",
          new DialogUtil.onSubmitListener() {
            @Override
            public void doSubmit() {

            }
          });
      return;
    }
    isSelectCardFail = false;
    cardNumEt.setVisibility(View.GONE);
    cardNumTv.setText(TextUtil.Text(list.get(0).consumerCarNo));
    cardUserView.setVisibility(View.VISIBLE);
    cardUsernameTv.setText("姓名:" + TextUtil.Text(list.get(0).name));
    cardUserIdTv.setText("身份:" + TextUtil.Text(list.get(0).identityName));
    numSureTv.setText("重新开单");
  }

  public void ChangePoint(final List<PointBean> list) {
    PopUtil.showPointFilterList(context, pointTv, list, new PopUtil.ItemClickListener() {
      @Override
      public void click(int position) {
        pointTv.setText(TextUtil.Text(list.get(position).name));
        worker.getGoods(list.get(position).code);
        pointCode = list.get(position).code;
      }
    });
  }

}
